package test.test.one;

import test.test.one.levels.AbstractLevel;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

//TODO finish documentation
public class MainThread extends Thread {
	
	private static final String TAG = MainThread.class.getSimpleName();

	// Surface holder that can access the physical surface
	private SurfaceHolder surfaceHolder;
	
	//check
	private AbstractLevel level;
	
	// flag to hold game state 
	private boolean running;
	public void setRunning(boolean running) {
		this.running = running;
	}
	
	//new constructor
	
	public MainThread(SurfaceHolder surfaceHolder, AbstractLevel level) {
		super();
		this.surfaceHolder = surfaceHolder;
		this.level = level;
	}
	
	@Override
	public void run() {
		Canvas canvas;
		Log.d(TAG, "Starting game loop");
		while (running) {
			canvas = null;
			// try locking the canvas for exclusive pixel editing
			// in the surface
			try {
				canvas = this.surfaceHolder.lockCanvas();
				synchronized (surfaceHolder) {
					// update game state 
					this.level.update();
					// render state to the screen
					// draws the canvas on the panel
					this.level.render(canvas);				
				}
			} finally {
				// in case of an exception the surface is not left in 
				// an inconsistent state
				if (canvas != null) {
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}	// end finally
		}
	}
}
